/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmRenovaAlvara.java
 *
 * Created on 25/01/2010, 13:37:41
 */

package forms;

import classes.Estabelecimentos;
import classes.contrato;
import classes.contratos;
import classes.tecnicos;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import rad.Java.Common.DB.Search;

/**
 *
 * @author rogerio
 */
public class frmRenovaAlvara extends javax.swing.JFrame {
    private Estabelecimentos listEstab;
    private tecnicos listTecnico;
    private contrato c;
    private contratos list = new contratos();
    boolean status = true;
    Search busca;
    DefaultTableModel dtmEstab;

    String fHora = "HH:mm:ss";
    String fDia  = "dd/MM/yyyy";
    SimpleDateFormat sdf  = new SimpleDateFormat(fHora);
    SimpleDateFormat sdfD = new SimpleDateFormat(fDia);
    Date d = new Date();

    /** Creates new form frmRenovaAlvara */
    public frmRenovaAlvara() {
        initComponents();
        listEstab       = new Estabelecimentos();
        listTecnico     = new tecnicos();
        busca           = new Search();
        c               = new contrato();
        
        listEstab.fillList();
        listTecnico.fillList();
        fillComboBoxEstabelecimentos();
        fillComboBoxTecnico();
        timer1.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        timer1 = new org.netbeans.examples.lib.timerbean.Timer();
        btnEditar = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        jtpRenovaAlvara = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        txtPesquisa = new javax.swing.JTextField();
        btnPesquisar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbRenovaAlvara = new javax.swing.JTable();
        rbdAno = new javax.swing.JRadioButton();
        rbdEstabelecimento = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        cmbEstabelecimentos = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmbTecnico = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        labelHora = new javax.swing.JLabel();
        txtDataExpedicao = new javax.swing.JFormattedTextField();
        txtAno = new javax.swing.JFormattedTextField();
        labelData = new javax.swing.JLabel();
        txtDataPreenchimento = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtDuamDate = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        btnDeletar1 = new javax.swing.JButton();

        timer1.addTimerListener(new org.netbeans.examples.lib.timerbean.TimerListener() {
            public void onTime(java.awt.event.ActionEvent evt) {
                timer1OnTime(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar\\Renovar Alvará");
        setResizable(false);
        getContentPane().setLayout(null);

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/edit_32x32.png"))); // NOI18N
        btnEditar.setToolTipText("Editar");
        btnEditar.setName("btnEditar"); // NOI18N
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });
        getContentPane().add(btnEditar);
        btnEditar.setBounds(176, 237, 44, 45);

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/save_32x32.png"))); // NOI18N
        btnSalvar.setToolTipText("Salvar");
        btnSalvar.setName("btnSalvar"); // NOI18N
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        getContentPane().add(btnSalvar);
        btnSalvar.setBounds(247, 237, 44, 45);

        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/new_32x32.png"))); // NOI18N
        btnNovo.setToolTipText("Novo");
        btnNovo.setName("btnNovo"); // NOI18N
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        getContentPane().add(btnNovo);
        btnNovo.setBounds(105, 237, 44, 45);

        jtpRenovaAlvara.setName("jtpRenovaAlvara"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        txtPesquisa.setName("txtPesquisa"); // NOI18N

        btnPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/search_32x32.png"))); // NOI18N
        btnPesquisar.setToolTipText("Pesquisar");
        btnPesquisar.setName("btnPesquisar"); // NOI18N
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tbRenovaAlvara.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbRenovaAlvara.setName("tbRenovaAlvara"); // NOI18N
        jScrollPane1.setViewportView(tbRenovaAlvara);

        buttonGroup1.add(rbdAno);
        rbdAno.setText("Ano");
        rbdAno.setName("rbdAno"); // NOI18N

        buttonGroup1.add(rbdEstabelecimento);
        rbdEstabelecimento.setSelected(true);
        rbdEstabelecimento.setText("Estabelecimento");
        rbdEstabelecimento.setName("rbdEstabelecimento"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rbdAno)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbdEstabelecimento)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(rbdAno)
                        .addComponent(rbdEstabelecimento)
                        .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtpRenovaAlvara.addTab("Pesquisa", jPanel1);

        jPanel2.setName("jPanel2"); // NOI18N

        cmbEstabelecimentos.setName("cmbEstabelecimentos"); // NOI18N

        jLabel2.setText("Estabelecimento:");
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText("Técnico:");
        jLabel3.setName("jLabel3"); // NOI18N

        cmbTecnico.setName("cmbTecnico"); // NOI18N

        jLabel4.setText("Data Expedição:");
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText("Ano:");
        jLabel5.setName("jLabel5"); // NOI18N

        labelHora.setName("labelHora"); // NOI18N

        try {
            txtDataExpedicao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtDataExpedicao.setName("txtDataExpedicao"); // NOI18N

        try {
            txtAno.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtAno.setName("txtAno"); // NOI18N

        labelData.setName("labelData"); // NOI18N

        try {
            txtDataPreenchimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtDataPreenchimento.setName("txtDataPreenchimento"); // NOI18N

        jLabel1.setText("Data Preechimento");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel6.setText("Data Rec. DUAM");
        jLabel6.setName("jLabel6"); // NOI18N

        try {
            txtDuamDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtDuamDate.setName("txtDuamDate"); // NOI18N

        jLabel7.setText("Código:");
        jLabel7.setName("jLabel7"); // NOI18N

        lblCodigo.setFont(new java.awt.Font("Ubuntu", 0, 18));
        lblCodigo.setText("0");
        lblCodigo.setName("lblCodigo"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDuamDate, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                        .addComponent(txtDataPreenchimento, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel7)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblCodigo))
                                    .addComponent(cmbTecnico, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                        .addComponent(txtDataExpedicao, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(cmbEstabelecimentos, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(152, 152, 152))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(50, 50, 50)
                        .addComponent(labelData, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelHora, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {labelData, labelHora});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbEstabelecimentos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTecnico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(6, 6, 6)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtDataExpedicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDataPreenchimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel7)
                    .addComponent(lblCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtDuamDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(labelData, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                    .addComponent(labelHora, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {labelData, labelHora});

        jtpRenovaAlvara.addTab("Principal", jPanel2);

        getContentPane().add(jtpRenovaAlvara);
        jtpRenovaAlvara.setBounds(0, 0, 393, 231);

        btnDeletar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/exit_32x32.png"))); // NOI18N
        btnDeletar1.setToolTipText("Sair");
        btnDeletar1.setName("btnExit"); // NOI18N
        btnDeletar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletar1ActionPerformed(evt);
            }
        });
        getContentPane().add(btnDeletar1);
        btnDeletar1.setBounds(318, 237, 44, 45);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-401)/2, (screenSize.height-325)/2, 401, 325);
    }// </editor-fold>//GEN-END:initComponents

   
    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        Date date = new Date();
        SimpleDateFormat sss  = new SimpleDateFormat("yyyy");

        clear();

        cmbEstabelecimentos.requestFocus();
        jtpRenovaAlvara.setSelectedIndex(1);
        c.clear();
        status = true;
        txtDataExpedicao.setText(sdfD.format(date));
        txtDataPreenchimento.setText(sdfD.format(date));
        txtDuamDate.setText(sdfD.format(date));
        txtAno.setText(sss.format(date));

        lblCodigo.setText("0");
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        try {
            pesquisar();
        } catch (SQLException ex) {
            Logger.getLogger(frmRenovaAlvara.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnPesquisarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
            try {
                editar();
            } catch (SQLException ex) {
                Logger.getLogger(frmRenovaAlvara.class.getName()).log(Level.SEVERE, null, ex);
            }       
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        salvar();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void timer1OnTime(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timer1OnTime
        d = new Date();
        labelHora.setText("Hora.: "+sdf.format(d));
        labelData.setText("Data.: "+sdfD.format(d));
    }//GEN-LAST:event_timer1OnTime

    private void btnDeletar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletar1ActionPerformed
        this.dispose();
}//GEN-LAST:event_btnDeletar1ActionPerformed

    //<editor-fold defaultstate="collapsed" desc="Fuctions">
    private void fillComboBoxEstabelecimentos()
    {
        for(int i = 0; i < listEstab.count(); i++)
        {
            cmbEstabelecimentos.addItem(listEstab.get(i).getEstab_name());
        }
    }

    private void fillComboBoxTecnico()
    {
        for(int i = 0; i < listTecnico.count(); i++)
        {
            cmbTecnico.addItem(listTecnico.get(i).getTecnico_name());
        }
    }

    private void clear()
    {
        txtPesquisa.setText("");
        txtDataExpedicao.setText("");
        txtDataPreenchimento.setText("");
        txtDuamDate.setText("");
        txtAno.setText("");
        lblCodigo.setText("0");
    }

    private void pesquisar() throws SQLException
    {
        busca.prepare();
        String sql = "";
        if(txtPesquisa.toString().equals(""))
        {
            JOptionPane.showMessageDialog(null, "Preencha o campo pesquisa");
            return;
        }
        String value = "contratos.id as cont_id, estab_name, contratos.ano as cont_ano, " +
                "tecnico.tecnico_name as tec_name, estabelecimentos.id as estab_id, tecnico.id as tec_id";
        
        busca.setFields(value);
        busca.setTable("contratos");
        busca.setTable("estabelecimentos", "contratos.estabelecimentos_id = estabelecimentos.id");
        busca.setTable("tecnico", "tecnico.id = contratos.tecnico_id");


        if (rbdEstabelecimento.isSelected()) {
            busca.setConditionalWhere("estab_name LIKE '"+txtPesquisa.getText()+"%'");
        } else {
            busca.setConditionalWhere("ano LIKE '"+ txtPesquisa.getText()+"%'");
        }

        sql = busca.getSql();
        if (!busca.execute()) {
            JOptionPane.showMessageDialog(null, "Erro:"+ busca.getMessageError());
            return;
        }
        fillGridView();
    }

    private void fillGridView() throws SQLException
    {
        String[] colunas = new String[]{"Codigo","Estabelecimento","Ano","Tecnico"};
        String[][] dados = new String[][]{{}};
        dtmEstab = new DefaultTableModel(dados, colunas);

        String contrato[] = new String[4];
        int aux = 0;
        while(busca.next())
        {
            contrato[0] = busca.getValue("cont_id").toString();
            contrato[1] = busca.getValue("estab_name").toString();
            contrato[2] = busca.getValue("cont_ano").toString();
            contrato[3] = busca.getValue("tec_name").toString();
            dtmEstab.addRow(contrato);
        }
        dtmEstab.removeRow(0);
        tbRenovaAlvara.setModel(dtmEstab);
    }

    private void editar() throws SQLException
    {
        c.setId(idGredViewSelectedRow());
        if(!c.get())
        {
            JOptionPane.showMessageDialog(null, "Erro:"+ c.getErrorMessage());
            return;
        }
        clear();
        fillEdits();
        status = false;
        jtpRenovaAlvara.setSelectedIndex(1);
    }

    private String idGredViewSelectedRow()
    {
        int  index = tbRenovaAlvara.getSelectedRow();
        String id  = tbRenovaAlvara.getValueAt(index,0).toString();
        return id;
    }

    private void fillEdits()
    {
        txtAno.setText(c.getAno());
        txtDataExpedicao.setText(c.getDate_expedicao());
        txtDataPreenchimento.setText(c.getDate());
        txtDuamDate.setText(c.getDuamDate());
        rad.Java.Common.Util.Functions.setComboBox(listEstab, cmbEstabelecimentos, c.getEstabelecimentos_id());
        rad.Java.Common.Util.Functions.setComboBox(listTecnico, cmbTecnico, c.getTecnico_id());
        lblCodigo.setText(c.getId());
    }

    private void salvar()
    {
        try {
            int comboEstab = cmbEstabelecimentos.getSelectedIndex();
            int comboTecn = cmbTecnico.getSelectedIndex();
            if (txtAno.getText().equals("") || txtDataExpedicao.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Preencha todos campos");
                return;
            }

            c.setAno(txtAno.getText());
            c.setDate(txtDataPreenchimento.getText());
            c.setEstabelecimentos_id(listEstab.get(comboEstab).getId());
            c.setTecnico_id(listTecnico.get(comboTecn).getId());
            c.setDate_expedicao(txtDataExpedicao.getText().toString());
            c.setDuamDate(txtDuamDate.getText());
            String mensagem = "";
            if (status) {
                if (list.searchByYear(listEstab.get(comboEstab).getId(), txtAno.getText()))
                {
                    JOptionPane.showMessageDialog(null, "Empresa já possui um Alvará cadastrado para esse ano!");
                    return;
                }
                if (c.save()) {
                    mensagem = "Registro salvo com sucesso";
                } else {
                    mensagem = "Erro ao tentar gravar o registro";
                }
            } else {
                if (c.update()) {
                    mensagem = "Registro salvo com sucesso";
                } else {
                    mensagem = "Erro ao tentar gravar o registro";
                }
            }
            JOptionPane.showMessageDialog(null, mensagem);
            status = true;
            limpaDVG();
            clear();
            jtpRenovaAlvara.setSelectedIndex(0);
        } catch (SQLException ex) {
            Logger.getLogger(frmRenovaAlvara.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void limpaDVG()
    {
        String[] colunas = new String[]{"Codigo","Estabelecimento","Ano","Tecnico"};
        String[][] dados = new String[][]{{}};
        dtmEstab = new DefaultTableModel(dados, colunas);
        tbRenovaAlvara.setModel(dtmEstab);
    }

    //</editor-fold>
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmRenovaAlvara().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeletar1;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cmbEstabelecimentos;
    private javax.swing.JComboBox cmbTecnico;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jtpRenovaAlvara;
    private javax.swing.JLabel labelData;
    private javax.swing.JLabel labelHora;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JRadioButton rbdAno;
    private javax.swing.JRadioButton rbdEstabelecimento;
    private javax.swing.JTable tbRenovaAlvara;
    private org.netbeans.examples.lib.timerbean.Timer timer1;
    private javax.swing.JFormattedTextField txtAno;
    private javax.swing.JFormattedTextField txtDataExpedicao;
    private javax.swing.JFormattedTextField txtDataPreenchimento;
    private javax.swing.JFormattedTextField txtDuamDate;
    private javax.swing.JTextField txtPesquisa;
    // End of variables declaration//GEN-END:variables
}
